<template>
  <div class="edit_profile">
    <myhead title="编辑个人信息">
      <van-icon name="arrow-left" slot="left" @click="$router.back()" />
      <van-icon
        name="wap-home-o"
        slot="right"
        @click="$router.push({ path: '/index' })"
      />
    </myhead>
    <div class="userImg">
      <img :src="userinfo.head_img" alt="" />
      <van-uploader :after-read="afterRead" />
    </div>
  </div>
</template>

<script>
import myhead from "@/components/myhead.vue";
import { getUser, update } from "@/apis/user.js";
import axios from "@/utils/myaxios.js";
import { formdate } from "@/apis/fileUpload.js";
export default {
  data() {
    return {
      userinfo: {},
    };
  },
  components: {
    myhead,
  },
  methods: {
    async afterRead(file) {
      console.log(file);
      // 此时可以自行将文件上传至服务器
      let myfate = new FormData();
      myfate.append("file", file.file);
      let res = await formdate(myfate);
      console.log(res); // 文件上传成功
      //现在只是展示的更换图片 并没有实现真正的更新
      this.userinfo.head_img = axios.defaults.baseURL + res.data.data.url;
      // 要发送编辑用户信息的请求才可以
      let reslut = await update(this.userinfo.id, {
        head_img: res.data.data.url,
      });
      console.log(reslut);
    },
  },
  // 页面一加载就发送请求
  async mounted() {
    // 获取到id
    let id = this.$route.params.id;
    let res = await getUser(id);
    console.log(res);
    this.userinfo = res.data.data;
    if (this.userinfo.head_img) {
      this.userinfo.head_img = axios.defaults.baseURL + this.userinfo.head_img;
    } else {
      this.userinfo.head_img =
        axios.defaults.baseURL + "/uploads/image/pages.png";
    }
  },
};
</script>

<style lang="less" scoped>
.edit_profile {
  .userImg {
    position: relative;
    width: 100%;
    height: 150px;
    display: flex;
    justify-content: center;
    align-items: center;
    > img {
      height: 90 * 100vw/360;
      width: 90 * 100vw/360;
    }
    /deep/ .van-uploader__upload {
      height: 100 * 100vw/360;
      width: 100 * 100vw/360;
    }
    /deep/ .van-uploader {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      opacity: 0;
    }
  }
}
</style>